﻿
app.controller('IssueReportController', function ($scope, $http, $window, $compile, $filter, ipCookie, common, option, Upload) {
    $scope.result = {};
    $scope.dateOption = option.date;
    $scope.datetimeOption = option.datetime;

    $scope.GetNodeMenu = function (node) {
        mui.showLoading("正在加载..", "div");
        var hmenu = sessionStorage.getItem('IssueMenu');
        if (hmenu == null) {
            $http({
                method: 'POST',
                url: '../Account/GetMMenuList',
                data: { 'Node': node }
            })
                .success(function (ret) {
                    mui.hideLoading();
                    common.success($scope, null, ret);
                    if (ret.Code == 100) {
                        $scope.CheckMenuList = ret.Data;
                        sessionStorage.setItem("IssueMenu", JSON.stringify(ret.Data));
                    }
                    else {
                        mui.toast(ret.Msg);
                    }
                })
                .error(function (data, status, headers, config) {
                    mui.toast("请检查网络");
                });
        }
        else {
            $scope.CheckMenuList = JSON.parse(hmenu);
            mui.hideLoading();
        }
    }
	

	$scope.InitLxUpload = function(id,index){
		try{
		lx.media.chooseImage({
			count:1,
			sourceType:["album","camera"],
			quality:'high',
			success:function(res){
				var filelist = res.tempFiles;
				var filelist = res.tempFiles;
				var img = document.getElementById(id+index);
				img.src=filelist[0].base64;
				var file = $scope.base64ToFile(filelist[0].base64,filelist[0].name);
				Upload.upload({
							method: 'POST',
							url: '../HiddenTrouble/UploadFormImage',
							data: { "Category": 'IssueReport' },
							file: file
						}).success(function (ret) {
							common.success($scope, null, ret);
							if (ret.Code == 100) {
								for (var j = 0; j < $scope.FileObjList.length; j++) {
                                        if ($scope.FileObjList[j].Index == index) {
                                            var f = $scope.FileObjList[j];
                                            $scope.FileObjList.splice($.inArray(f, $scope.FileObjList, 1));
                                        }
                                    }
                                    var obj = {
                                        Index: index,
                                        ImageId: ret.Data
                                    };
                                    $scope.FileObjList.push(obj);
							}
							else {
							   mui.toast(ret.Msg);
							}
						})	
			}
		});
		}catch(error){
			mui.toast(error);
		}
	}
	

	$scope.base64ToFile = function(base64str,filename){
		try{
			const arr = base64str.split(',');
			const mimeType = arr[0].match(/:(.*?);/)[1]; // 获取 MIME 类型
			var byteCharacters = atob(arr[1]);
		  var byteArrays = [];
		  for (var offset = 0; offset < byteCharacters.length; offset += 1024) {
			var slice = byteCharacters.slice(offset, offset + 1024);
			var byteNumbers = new Array(slice.length);
			for (var i = 0; i < slice.length; i++) {
			  byteNumbers[i] = slice.charCodeAt(i);
			}
			var byteArray = new Uint8Array(byteNumbers);
			byteArrays.push(byteArray);
		  }
		  var file = new Blob(byteArrays, { type: mimeType });
		  file.lastModifiedDate = new Date();
		  file.name = filename;
		  return file;
		}catch(error){
			mui.toast(error);
		}						
	}

    $scope.InitParkPlace = function (placeid, addmodel) {
        if (placeid != "") {
            $http({
                method: 'POST',
                url: '../SafetyConfig/GetPlaceInfo',
                data: { "Id": placeid}
            })
                .success(function (ret) {
                    common.success($scope, null, ret);
                    if (ret.Code == 100) {
                        addmodel.ParkId = ret.Data.ParkInfo.Id+"";
                        $scope.MGetPlaceList(addmodel.ParkId);
                    }
                    else {
                        alertify.alert(ret.Msg);
                    }
                })
                .error(function (data, status, headers, config) {
                    alertify.alert("请检查网络");
                });
        }
    }

    $scope.GetParkList = function () {
        $scope.ParkList = [];
        $http({
            method: 'POST',
            url: '../SafetyConfig/GetParkList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.ParkList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }
    $scope.MGetPlaceList = function (id) {
        $scope.PlaceList = [];
        $http({
            method: 'POST',
            url: '../IssueReport/GetParkPlace',
            data: { "ParkId": id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.PlaceList = ret.Data;
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                mui.toast("请检查网络");
            });
    }
    $scope.GetPlaceList = function (control, id, defaultvalue) {
        if (id == null || id == "")
            return false;
        $("#" + control).html($compile('<option value="" selected>请选择场所</option>')($scope));
        $("#" + control).selectpicker('refresh');
        $http({
            method: 'POST',
            url: '../IssueReport/GetParkPlace',
            data: { "ParkId": id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $.each(ret.Data, function (i, n) {
                        if (defaultvalue != null) {
                            if (n.Id == defaultvalue)
                                $("#" + control).append($compile("<option selected='selected' value=\"" + n.Id + "\">" + n.PlaceName + "</option>")($scope));
                            else
                                $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.PlaceName + "</option>")($scope));
                        }
                        else {
                            $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.PlaceName + "</option>")($scope));
                        }
                    })
                    $("#" + control).selectpicker('refresh');
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.AddIssueReport = function (model) {
        if (model.PlaceId == null || model.PlaceId == "0") {
            alertify.alert("请选择场所");
            return false;
        }
        if (model.Description == null || model.Description == "") {
            alertify.alert("填写问题描述");
            return false;
        }
        var flag = $("#level2").prop("checked");
        if (flag) {
            model.ReportTo = 2;
        }
        else {
            model.ReportTo = 1;
        }
        var files = document.querySelector('input[type=file]').files;
        Upload.upload({
            method: 'POST',
            url: '../IssueReport/IssueFormAdd',
            data: { 'model': model },
            file: files
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    alertify.alert("问题上报成功！");

                    setTimeout(function () {
                        location.href = "MyIssueReport";
                    }, 2000)
                } else
                    alertify.alert(ret.Message);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }

    $scope.MAddIssueReport = function (model,pagename,guest) {
        if (model.PlaceId == null || model.PlaceId == "") {
            mui.toast("请选择场所");
            return false;
        }
        if (model.Description == null || model.Description == "") {
            mui.toast("填写问题描述");
            return false;
        }
        var flag = $("#level2").prop("checked");
        if (flag) {
            model.ReportTo = 2;
        } else {
            model.ReportTo = 1;
        }
        for (var i = 0; i < $scope.FileObjList.length; i++) {
            $scope.FileList.push($scope.FileObjList[i].ImageId);
        }
        $http({
            method: 'POST',
            url: '../IssueReport/IssueFormAdd',
            data: { 'model': model, 'FileList': $scope.FileList }
        })
            .success(function (ret) {
                if (ret.Code == 100) {
                    mui.toast("问题上报成功！");
                    setTimeout(function () {
                        if (pagename == "../Home/MPlaceWork") {
                            location.href = '../Home/MPlaceWork?PlaceId=' + model.PlaceId + "&RoomId=" + model.RoomId + "&PlaceName=" + model.PlaceName;
                        }
                        else {
                            location.href = "MMyIssueReport?g=" + guest;
                        }
                       
                    }, 2000)
                } else
                    mui.toast(ret.Message);
            })
            .error(function (data, status, headers, config) {
                common.error($scope);
            })
    }

    $scope.GetIssueReportPageList = function (model, page) {
        $scope.IssueReportList = [];
        $scope.DataLoading = true;
        $http({
            method: 'POST',
            url: '../IssueReport/GetIssueReportPageList',
            data: { 'model': model, 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                $scope.DataLoading = false;
                if (ret.Code == 100) {
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    $scope.IssueReportList = ret.Data.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                $scope.DataLoading = false;
                alertify.alert("请检查网络");
            });
        $http({
            method: 'POST',
            url: '../IssueReport/GetStatusCount',
            data: { 'model': model }
        }).success(function (ret) {
            common.success($scope, null, ret);
            $scope.DataLoading = false;
            if (ret.Code == 100) {
                $scope.StatusCount = ret.Data;
            }
            else {
                alertify.alert(ret.Msg);
            }
        })
            .error(function (data, status, headers, config) {
                $scope.DataLoading = false;
                alertify.alert("请检查网络");
            });

    }

    $scope.GetMyIssueReportPageList = function (model, page) {
        $scope.IssueReportList = [];
        $scope.DataLoading = true;
        $http({
            method: 'POST',
            url: '../IssueReport/GetMyIssueReportPageList',
            data: { 'model': model, 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                $scope.DataLoading = false;
                if (ret.Code == 100) {
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    $scope.IssueReportList = ret.Data.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                $scope.DataLoading = false;
                alertify.alert("请检查网络");
            });

    }

    $scope.BindDepartmentList = function (control, defaultvalue) {
        $http({
            method: 'POST',
            url: '../HiddenTrouble/GetDepartmentList'
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $.each(ret.Data, function (i, n) {
                        if (n.DepartmentName != "系统支持") {
                            if (defaultvalue != null) {
                                if (n.Id == defaultvalue)
                                    $("#" + control).append($compile("<option selected='selected' value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                                else
                                    $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                            }
                            else {
                                $("#" + control).append($compile("<option value=\"" + n.Id + "\">" + n.DepartmentName + "</option>")($scope));
                            }
                        }
                    })
                    $("#" + control).selectpicker('refresh');
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.DeleteIssueReport = function (id, searchmodel, page) {
        alertify.okBtn("确认")
            .cancelBtn("取消").confirm("确认此操作？", function (ev) {
                ev.preventDefault();
                $scope.PageLoading = true;
                $http({
                    method: 'POST',
                    url: '../IssueReport/DeleteIssueReport',
                    data: { 'Id': id }
                })
                    .success(function (ret) {
                        common.success($scope, null, ret);
                        $scope.PageLoading = false;
                        if (ret.Code == 100) {
                            $scope.AlertBox("删除成功！");
                            $scope.GetIssueReportPageList(searchmodel, page);
                        }
                        else {
                            alertify.alert(ret.Msg);
                        }
                    })
                    .error(function (data, status, headers, config) {
                        alertify.alert("请检查网络");
                    });
            }, function (ev) {
                ev.preventDefault();
            });

    }

    $scope.DealTaskIssue = function (id) {
        setTimeout(function () {
            if (id!=null && id != "") {
                $scope.IsTask = true;
                $("#btn_deal_" + id).click();
            }
            else {
                $scope.IsTask = false;
            }
            console.log($scope.IsTask);
        }, 2000);
       
        //if (id != "") {
        //    $http({
        //        method: 'POST',
        //        url: '../IssueReport/GetIssueReportDetail',
        //        data: { 'Id': id }
        //    })
        //        .success(function (ret) {
        //            common.success($scope, null, ret);
        //            if (ret.Code == 100) {
        //                $scope.IssueDetail = ret.Data;
        //                $scope.InitIssueDealModel($scope.IssueDetail);

        //            }
        //            else {
       
        //            }
        //        })
        //        .error(function (data, status, headers, config) {
        //            alertify.alert("请检查网络");
        //        });
        //}
    }

    $scope.GetIssueDetailModel = function (model) {
        $scope.IssueDetail = model;
    }

    $scope.InitIssueDealModel = function (model) {
        $scope.IssueDeal = {};
        $scope.IssueDeal.IssueId = model.Id;
        $scope.IssueDeal.Remark = "";
    }

    $scope.DealIssue = function (model, status, searchmodel, page) {
        model.Status = status;
        alertify.okBtn("确认")
            .cancelBtn("取消").confirm("确认此操作？", function (ev) {
                ev.preventDefault();
                $scope.PageLoading = true;
                $http({
                    method: 'POST',
                    url: '../IssueReport/DealIssue',
                    data: { 'model': model }
                })
                    .success(function (ret) {
                        common.success($scope, null, ret);
                        $scope.PageLoading = false;
                        if (ret.Code == 100) {
                            if (ret.Data != null) {
                                alertify.alert("操作成功，正在跳转到问题登记界面...");
                                setTimeout(function () {
                                    location.href = "../HiddenTrouble/HiddenTroubleEdit?FormId=" + ret.Data + "&page=1&pagename=HiddenTroubleRectification";
                                }, 3000);
                            }
                            else {
                                alertify.alert("操作成功");
                                $("#close2").click();
                                if ($scope.IsTask) {
                                    location.href = "../Home/WorkTask";
                                }
                                $scope.GetIssueReportPageList(searchmodel, page);
                            }
                        }
                        else {
                            alertify.alert("操作成功，正在跳转到问题登记界面...");
                        }
                    })
                    .error(function (data, status, headers, config) {
                        alertify.alert("请检查网络");
                    });
            }, function (ev) {
                ev.preventDefault();
            });
    }

    $scope.GetDealIssueList = function (Id) {
        $scope.DealList = [];
        $http({
            method: 'POST',
            url: '../IssueReport/GetDealResult',
            data: { 'Id': Id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.DealList = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.GetIssueDetail = function (Id) {
        $scope.IssueDetail = {};
        $http({
            method: 'POST',
            url: '../IssueReport/GetIssueReportDetail',
            data: { 'Id': Id }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.IssueDetail = ret.Data;
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.InitImgeUpload = function () {
        setTimeout(function () {
            for (var i = 0; i < $scope.ImageCount.length; i++) {
                var imagebox = "#imagebox_" + $scope.ImageCount[i];
                var dragImgUpload = new DragImgUpload(imagebox, {
                    callback: function (files,optionId,index) {
                        //回调函数，可以传递给后台等等
                        var file = files[0];
                        Upload.upload({
                            method: 'POST',
                            url: '../HiddenTrouble/UploadFormImage',
                            data: { "Category": 'IssueReport' },
                            file: file
                        })
                            .success(function (ret) {
                                $scope.Submiting = false;
                                if (ret.Code == 100) {
                                    for (var j = 0; j < $scope.FileObjList.length; j++) {
                                        if ($scope.FileObjList[j].Index == index) {
                                            var f = $scope.FileObjList[j];
                                            $scope.FileObjList.splice($.inArray(f, $scope.FileObjList, 1));
                                        }
                                    }
                                    var obj = {
                                        Index: index,
                                        ImageId: ret.Data
                                    };
                                    $scope.FileObjList.push(obj);
                                    console.log($scope.FileObjList);

                                } else
                                    alertify.alert(ret.Msg);
                            })
                            .error(function (data, status, headers, config) {
                                common.error($scope);
                                mui.toast("请检查网络");
                            })
                    }
                }, "", $scope.ImageCount[i]);
            }
        }, 2000);
    }

    $scope.InitMyIssueReport = function () {
        $scope.PageIndex = 1;
        mui.init({
            pullRefresh: {
                container: '#pullrefresh',
                down: {
                    style: 'circle',
                    auto: true,//可选,默认false.首次加载自动上拉刷新一次
                    callback: function () {
                        setTimeout(function () {
                            $scope.MGetMyIssueReport($scope.SearchModel, 1);
                            mui('#pullrefresh').pullRefresh().refresh(true);
                            mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
                        }, 1500);

                    }
                }, up: {
                    auto: false,
                    contentrefresh: '正在加载...',
                    callback: function () {
                        $scope.MGetMyIssueReport($scope.SearchModel, $scope.PageIndex + 1);
                    },

                }
            }
        });
    }

    $scope.MGetMyIssueReport = function (model, page) {
        if (page == 1) {
            $scope.IssueReportList = [];
        }
        $scope.PageIndex = page;
        $http({
            method: 'POST',
            url: '../IssueReport/GetMyIssueReportPageList',
            data: { 'model': model },
            params: { 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    for (var i = 0; i < ret.Data.Data.length; i++) {
                        $scope.IssueReportList.push(ret.Data.Data[i]);
                    }
                    if (ret.Data.Data.length == 0) {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
                    }
                    else {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(false);
                    }
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }


    $scope.MGetIssueReportDealList = function (model, page) {
        if (page == 1) {
            $scope.IssueReportList = [];
        }
        $scope.PageIndex = page;
        $http({
            method: 'POST',
            url: '../IssueReport/GetIssueReportPageList',
            data: { 'model': model },
            params: { 'page': page }
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.TotalCount = ret.Data.TotalItemCount;
                    for (var i = 0; i < ret.Data.Data.length; i++) {
                        $scope.IssueReportList.push(ret.Data.Data[i]);
                    }
                    if (ret.Data.Data.length == 0) {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
                    }
                    else {
                        mui('#pullrefresh').pullRefresh().endPullupToRefresh(false);
                    }
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.InitDealIssueReport = function () {
        $scope.PageIndex = 1;
        mui.init({
            pullRefresh: {
                container: '#pullrefresh',
                down: {
                    style: 'circle',
                    auto: true,//可选,默认false.首次加载自动上拉刷新一次
                    callback: function () {
                        setTimeout(function () {
                            $scope.MGetIssueReportDealList($scope.SearchModel, 1);
                            mui('#pullrefresh').pullRefresh().refresh(true);
                            mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
                        }, 1500);

                    }
                }, up: {
                    auto: false,
                    contentrefresh: '正在加载...',
                    callback: function () {
                        $scope.MGetIssueReportDealList($scope.SearchModel, $scope.PageIndex + 1);
                    },

                }
            }
        });
    }


    $scope.GetResponsible = function (id) {
        if (id == null) {
            return false;
        }
        $http({
            method: 'POST',
            url: '../IssueReport/GetPlaceResponsible',
            data: { 'PlcaeId': id },
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.PlaceUser = ret.Data;
                }
                else {
                    alertify.alert(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.MGetResponsible = function (id) {
        if (id == null || id=='') {
            return false;
        }
        $http({
            method: 'POST',
            url: '../IssueReport/GetPlaceResponsible',
            data: { 'PlcaeId': id },
        })
            .success(function (ret) {
                common.success($scope, null, ret);
                if (ret.Code == 100) {
                    $scope.PlaceUser = ret.Data;
                }
                else {
                    mui.toast(ret.Msg);
                }
            })
            .error(function (data, status, headers, config) {
                alertify.alert("请检查网络");
            });
    }

    $scope.MDealIssue = function (model, status,pagename) {
        model.Status = status;
        var msg = "";
        if (status == 3) {
            msg = "确认关闭该问题？";
        } else {
            msg = "确认问题治理流程？";
        }
        mui.confirm(msg, '系统提醒', ['否', '是'], function (e) {
            if (e.index == 1) {
                $scope.PageLoading = true;
                $http({
                    method: 'POST',
                    url: '../IssueReport/DealIssue',
                    data: { 'model': model }
                })
                    .success(function (ret) {
                        common.success($scope, null, ret);
                        $scope.PageLoading = false;
                        if (ret.Code == 100) {
                            if (ret.Data != null) {
                                mui.alert('操作成功,正在跳转到问题登记界面', '系统提醒', function () {
                                    location.href = "../HiddenTrouble/MHiddenTroubleEdit?FormId="+ret.Data;
                                });
                            }
                            else {
                                if (pagename != '') {
                                    mui.alert('操作成功,返回待办列表', '系统提醒', function () {
                                        location.href = pagename;
                                    });
                                }
                                else {
                                    mui.alert('操作成功,返回待处理列表', '系统提醒', function () {
                                        location.href = "MIssueDealList";
                                    });
                                }
                            }
                        }
                        else {
                            mui.toast(ret.Msg);
                        }
                    })
                    .error(function (data, status, headers, config) {
                        mui.toast("请检查网络");
                    });
            } else {
                //mui.toast("");
            }
        })
    }

});